import xss from 'xss'

const options = {
  css: false,
  onTag(tag, html, options) {
    if (tag === 'iframe') {
      return html.replace(/javascript:?/, '')
    }
  },
  // 避免把页面样式过滤掉
  onIgnoreTagAttr(tag, name, value, isWhiteAttr) {
    // 过滤掉标签上的事件
    if (/^[^on]/.test(name)) {
      return name + '="' + xss.escapeAttrValue(value) + '"'
    }
  },
}
const filter = new xss.FilterXSS(options)

const filterHtmlXss = val =>
  filter
    .process(val)
    .replace('&lt;html&gt;', '<html>')
    .replace('&lt;body&gt;', '<body>')
    .replace('&lt;/body&gt;', '</body>')
    .replace('&lt;/html&gt;', '</html>')
    .replace('&lt;source', '<source')
    .replace('&gt;</video>', '></video>')

const htmlXss = {
  bind(el, binding) {
    el.innerHTML = filterHtmlXss(binding.value)
  },
  update: function (el, binding) {
    el.innerHTML = filterHtmlXss(binding.value)
  },
  unbind(el) {
    el.innerHTML = ''
  },
}

export default htmlXss
